package com.hkyp.ss.course.provider.impl;

import com.hkyp.ss.course.apis.ReplyService;
import com.hkyp.ss.course.apis.dto.common.PageReq;
import com.hkyp.ss.course.apis.dto.common.PageResp;
import com.hkyp.ss.course.apis.dto.request.ReplyDTO;
import com.hkyp.ss.course.apis.dto.response.SecCommentVO;
import com.hkyp.ss.course.apis.exception.ServiceException;
import com.hkyp.ss.course.apis.utils.BeanMapper;
import com.hkyp.ss.course.apis.utils.MyReflectionUtil;
import com.hkyp.ss.course.provider.model.Comment;
import com.hkyp.ss.course.provider.model.Reply;
import com.hkyp.ss.course.provider.model.User;
import com.hkyp.ss.course.provider.repository.CommentRepository;
import com.hkyp.ss.course.provider.repository.ReplyRepository;
import com.hkyp.ss.course.provider.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Service(version = "1.0")
@Transactional(rollbackFor = Exception.class)
public class ReplyServiceImpl implements ReplyService {


    @Autowired
    ReplyRepository replyRepository;

    @Autowired
    UserRepository userRepository;

    @Autowired
    CommentRepository commentRepository;


    // 返回评论列表页面
    @Override
    @Transactional(readOnly = true)
    public PageResp<SecCommentVO> selectSecondCommentList(Long parentId, PageReq pageReq) {

        Reply reply = new Reply();
        reply = MyReflectionUtil.byField(reply);

        reply.setParentId(parentId);

        reply.setStatus(0);

        Example<Reply> commentExample = Example.of(reply);

        Page<Reply> pageResp = replyRepository.findAll(commentExample,pageReq.toPageable());

        List<Reply> replyList = pageResp.getContent();

        // 用set可以去除重复元素
        Set<Long> fromUserIdsSet = replyList
                .stream()
                .map(Reply::getFromId)
                .collect(Collectors.toSet());
        log.info("fromIds: --->"+fromUserIdsSet);
        Set<Long> allUserIdsSet = replyList.stream()
                .map(Reply::getToId)
                .collect(Collectors.toSet());
        log.info("toIds: --->"+allUserIdsSet);
        allUserIdsSet.addAll(fromUserIdsSet);

        log.info("allIds: --->"+allUserIdsSet);

        List<User> userList = userRepository.findAllById(allUserIdsSet);

        // 转map
        Map<Long,User> userMap = userList
                .stream()
                .collect(Collectors.toMap(User::getId, user -> user));

        List<SecCommentVO> SecCommentVOList = new ArrayList<>();

        replyList.forEach( reply1 -> {

            List<SecCommentVO.CommentUser> list = new ArrayList<>();
            SecCommentVO secCommentVO = new SecCommentVO();
            secCommentVO.setId(reply1.getId());
            secCommentVO.setReplyMsg(reply1.getReplyMsg());
            secCommentVO.setUserLike(reply1.getUserLike());
            secCommentVO.setIssueTime(reply1.getCreateAt());

            User userFrom = userMap.get(reply1.getFromId());
            SecCommentVO.CommentUser fromUser = secCommentVO.new CommentUser();
            fromUser.setUid(userFrom.getId());
            fromUser.setAvatar(userFrom.getAvatar());
            fromUser.setNickName(userFrom.getNickName());
            fromUser.setRole(1);

            User userTo = userMap.get(reply1.getToId());
            SecCommentVO.CommentUser toUser = secCommentVO.new CommentUser();
            toUser.setUid(userTo.getId());
            toUser.setNickName(userTo.getNickName());
            toUser.setAvatar(userTo.getAvatar());
            toUser.setRole(0);
            list.add(fromUser);
            list.add(toUser);
            secCommentVO.setUsers(list);
            SecCommentVOList.add(secCommentVO);
        });


        return new PageResp<SecCommentVO>(pageResp,SecCommentVOList);
    }

//    @Transactional(rollbackFor=Exception.class)
//    @Override
    public void addReply(ReplyDTO replyDTO) {

        Reply reply = BeanMapper.map(replyDTO, Reply.class);

        reply.setFromId(replyDTO.getUserId());

        reply.setCreateAt(System.currentTimeMillis());
        replyRepository.save(reply);

        Comment comment = commentRepository.findById(replyDTO.getParentId())
                          .orElseThrow(() -> new ServiceException("您输入评论id(父id)不存在"));
        comment.setCommentNum(comment.getCommentNum()+1);
        commentRepository.save(comment);
    }


    @Override
    public void saveReply(List courseComment) {
        System.out.println(replyRepository.saveAll(courseComment));
    }


}
